const app = getApp();
const api = require('../../utils/api');
import QRCode from '../../utils/weapp-qrcode'; //引入生成二维码的插件

//初始化预约时间可选范围
let now = new Date(); //现在时间
let year = now.getFullYear();
let month = now.getMonth() + 1;
let day = now.getDate();
let startDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day); //格式化日期

Page({
    data: {
        isStaff: false, //是否店主or管理员

        id: '',
        orderDetail: '',
        shopDetail: '',
        productList: [],

        showWriteoffQrcode: false, //核销二维码弹窗
        writeoffQrcodeUrl: '', //核销二维码链接

        showEditBookTime: false,
        editBookTimeRemark: '', //修改备注
        newBookDate: '', //预约日期
        newBookTime: '', //预约时间
        startDate: startDate,

        showRefund: false, // 退款弹窗
        refundReasonList: ['顾客不想要了', '拍错/多拍/重复下单', '商品信息描述不符', '商品损坏/有污渍', '商品漏发/少发', '发错货/款式/型号/尺寸不对', '效果与预期不符', '其他'],
        refundReason: '', //退款原因
        refundReasonText: '', //退款原因文字
        refundReasonOther: '', //退款其他原因
    },
    onLoad(options) {
        if(options.id) {
            this.setData({
                id: options.id
            });
        }
        this.setData({
            isStaff: options.type ? true : false
        });
        
        this.getOrderDetail();
    },
    onShow() {
        
    },

    getOrderDetail() { //获取订单详情
        api.post(`/order/detail?orderId=${this.data.id}`)
            .then(res => {
                // 整理数据
                let data = res;
                data.payableAmountShow = res.payableAmount.toFixed(2);
                data.createTime = app.filterDate(res.createTime);
                data.payTime = res.payTime ? app.filterDate(res.payTime) : '-';
                data.pickupTime = res.pickupTime ? app.filterDate(res.pickupTime) : '-';
                data.planPickupTime = res.planPickupTime ? app.filterDate(res.planPickupTime) : '';
                // 整理商品
                let list = data.skuList;
                list.forEach(item => {
                    item.price = item.price.toFixed(2);
                    item.memberPrice = item.memberPrice.toFixed(2);
                });

                this.setData({
                    orderDetail: data,
                    productList: list,
                });

                if(data.shopId && !data.pickupName) {
                    this.getStoreInfo(data.shopId);
                }
            })
    },
    getStoreInfo(id) { //获取店铺信息
        api.post('/shop/detail?shopId=' + id)
            .then(res => {
                let detail = res;
                //整理营业时间
                let businessBeginTime = detail.businessBeginTime.split(':');
                let businessEndTime = detail.businessEndTime.split(':');
                detail.businessTime = businessBeginTime[0] + ':' + businessBeginTime[1] + '~' + businessEndTime[0] + ':' + businessEndTime[1];
                this.setData({
                    shopDetail: detail,
                });
            })
    },

    // 订单操作
    callPhone() { //拨打电话
        wx.makePhoneCall({
            phoneNumber: this.data.orderDetail.pickupPhone
        })
    },

    cancelOrder() { //取消订单
        wx.showModal({
            title: '温馨提示',
            content: `您是否确认取消订单？取消操作无法撤销。`,
            success: res => {
                if(res.confirm) {
                    api.post('/order/cancel?id=' + this.data.id)
                        .then(() => {
                            wx.showToast({
                                title: '订单已取消',
                                icon: 'none'
                            });

                            this.getOrderDetail();
                        })
                }
            }
        });
    },
    payOrder() { //去支付
        let url = this.data.orderDetail.orderType == 1 && this.data.isStaff ? `/pages/orderPay/orderPay?id=${this.data.id}&dir=1` : `/pages/orderPay/orderPay?id=${this.data.id}`
        wx.navigateTo({
            url: url,
        });
    },
    writeOffOrder() { //核销订单
        this.setData({
            showWriteoffQrcode: true
        });

        this.createWriteoffQrcode(this.data.id);
    },
    closeWriteoff() {
        this.setData({
            showWriteoffQrcode: false
        });
    },
    createWriteoffQrcode(id) { //生成二维码
        let text = {
            k: 'ORDER_WRITEOFF',
            v: {
                id: id
            }
        }
        new QRCode('myQrcode', {
            text: JSON.stringify(text),
            width: this.createRpx2px(500),
            height: this.createRpx2px(500),
            padding: 12, // 生成二维码四周自动留边宽度，不传入默认为0
            correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
            callback: res => {
                this.setData({
                    writeoffQrcodeUrl: res.path
                });
            }
        });
    },
    createRpx2px(rpx) {
        return wx.getWindowInfo().windowWidth / 750 * rpx
    },

    editBookTime() { //修改预约时间
        let bookDate = '';
        let bookTime = '';
        if(this.data.orderDetail.planPickupTime) {
            bookDate = this.data.orderDetail.planPickupTime.split(' ')[0];
            let time = this.data.orderDetail.planPickupTime.split(' ')[1];
            bookTime = time.split(':')[0] + ':' + time.split(':')[1];
        }
        this.setData({
            newBookDate: bookDate,
            newBookTime: bookTime,
            showEditBookTime: true
        });
    },
    closeEditBookTime() { //关闭预约时间
        this.setData({
            showEditBookTime: false,
            newBookDate: '',
            newBookTime: '',
            editBookTimeRemark: '',
        });
    },
    bindinput(e) { //输入框监听
        let item = e.currentTarget.dataset.item;
        let val = e.detail.value;
        
        this.setData({
            [item]: val
        });
    },
    bindDateChoose(e) { //选择日期
        let item = e.currentTarget.dataset.item;
        this.setData({
            [item]: e.detail.value,
        });
    },
    submitEditBookTime() {
        if(!this.data.newBookDate) {
            wx.showToast({
                title: '请选择预约日期！',
                icon: 'none'
            });
            return;
        }
        if(!this.data.newBookTime) {
            wx.showToast({
                title: '请选择预约时间！',
                icon: 'none'
            });
            return;
        }
        if(!this.data.editBookTimeRemark) {
            wx.showToast({
                title: '请输入修改原因！',
                icon: 'none'
            });
            return;
        }
        let params = {
            orderId: this.data.id,
            planPickupTime: this.data.newBookDate + ' ' + this.data.newBookTime + ':00',
            changeRemark: this.data.editBookTimeRemark,
        }
        api.post('/merchant/order/plan/time/change', params)
            .then(() => {
                wx.showToast({
                    title: '修改成功！',
                    icon: 'none'
                });
                this.closeEditBookTime();
                this.getOrderDetail();
            })
    },

    refundApply(e) { //提交退款申请（线下收款订单or账户余额支付订单）
        this.setData({
            showRefund: true,
        });
    },
    closeRefund() {
        this.setData({
            showRefund: false,
            refundReason: '',
            refundReasonText: '',
            refundReasonOther: '',
        });
    },
    chooseReason(e) { //选择退款原因
        this.setData({
            refundReasonText: this.data.refundReasonList[e.detail.value],
        });
    },
    submitRefund() {
        if(!this.data.refundReasonText) {
            wx.showToast({
                title: '请选择退款原因！',
                icon: 'none'
            });
            return;
        }
        if(this.data.refundReasonText == '其他' && !this.data.refundReasonOther) {
            wx.showToast({
                title: '请填写退款原因！',
                icon: 'none'
            });
            return;
        }

        let refundReason = this.data.refundReasonText == '其他' ? '其他：' + this.data.refundReasonOther : this.data.refundReasonText;
        let url = this.data.orderDetail.orderType == 5 ? `/payment/ccb/refund?orderNo=${this.data.orderDetail.orderNo}&refundReason=${refundReason}` : `/payment/account/refund?orderNo=${this.data.orderDetail.orderNo}&refundReason=${refundReason}`;

        api.post(url)
            .then(() => {
                wx.showToast({
                    title: '退款提交成功！',
                    icon: 'success'
                });
                
                this.closeRefund();
                this.getOrderDetail();
            })
    },

})